﻿#include"symboltable.h"
#include<string.h>
#include<malloc.h>
SymbolInf MakeSymbolInf(char* name, int type, int value)
{
	SymbolInf inf;
	strcpy(inf.name, name);
	inf.type = type;
	inf.value = value;
	inf.used = true;
	return inf;
}
bool InitSymbolTable(SymbolTable* stable, int s_size)
{
	if (stable == NULL)
		return false;
	stable->cur = 0;
	stable->cur_sta = 0;
	stable->max_size = s_size;
	stable->symbols = malloc(sizeof(SymbolInf) * s_size);
	if (stable->symbols != NULL)
		return true;
	return false;
}
void AddSymbol(SymbolTable* stable, SymbolInf sinf)
{
	if (stable == NULL || sinf.used == false)
		return;
	if (stable->cur >= stable->max_size)
	{
		SymbolInf* ls = stable->symbols;
		free((SymbolInf*)stable->symbols);
		stable->symbols = malloc(stable->max_size + 1024);
		for (int i = 0; i < stable->max_size; i++)
			stable->symbols[i] = ls[i];
		free((SymbolInf*)ls);
		stable->max_size = stable->max_size + 1024;
	}
	stable->symbols[stable->cur] = sinf;
	stable->cur++;
}
SymbolInf SearchSymbol(SymbolTable* stable, char* name)
{
	for (int i = 0; i < stable->max_size; i++)
	{
		if (strcmp(stable->symbols[i].name, name) == 0)
			return stable->symbols[i];
	}
	SymbolInf re = MakeSymbolInf("", 0, 0);
	re.used = false;
	return re;
}
bool SetSymbolType(SymbolTable* table, int idx, int ntype)
{
	if (table == NULL)
		return false;
	if (idx >= table->cur)
		return false;
	table->symbols[idx].type = ntype;
	return true;
}
bool SetSymbolValue(SymbolTable* table, int idx, int value)
{
	if (table == NULL)
		return false;
	if (idx >= table->cur)
		return false;
	table->symbols[idx].value = value;
	return true;
}
